package com.kcsj.dao;

import com.kcsj.domain.PayType;
import com.kcsj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 傅立贤
 * 29th Nov. 2020
 */
public class PayTypeDao {
    public static PayTypeDao payTypeDao = new PayTypeDao();

    private PayTypeDao() {
    }
    public static PayTypeDao getInstance() {
        return payTypeDao;
    }
    /**
     * @author 傅立贤
     * @param conn    数据库连接对象
     * @param id 需要查找的付款方式的id
     * @return payType 查找到的付款方式
     * @throws SQLException
     */
    public PayType find(Connection conn,Integer id) throws SQLException {
        String find_sql = "SELECT * FROM payType where id =?";
        PreparedStatement pstmt = conn.prepareStatement(find_sql);
        pstmt.setInt(1,id);
        ResultSet resultSet = pstmt.executeQuery();
        PayType payType = null;
        if (resultSet.next()) {
            String description = resultSet.getString("description");
            payType = new PayType(description,id);
        }
        JdbcHelper.close(resultSet,pstmt);
        return payType;
    }

    public Collection<PayType> findAll(Connection conn) throws SQLException {
        ArrayList<PayType> payTypes = new ArrayList<>();
        String find_sql = "SELECT * FROM payType";
        PreparedStatement pstmt = conn.prepareStatement(find_sql);
        ResultSet resultSet = pstmt.executeQuery();
        while (resultSet.next()) {
            Integer id = resultSet.getInt("id");
            String description = resultSet.getString("description");
            PayType payType = new PayType(description,id);
            payTypes.add(payType);
        }
        JdbcHelper.close(resultSet,pstmt);
        return payTypes;
    }
}
